package com.cenntro.common.mq.producer;

import javax.annotation.Resource;
import javax.annotation.Resources;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.cenntro.common.mq.constants.RocketMQErrorEnum;
import com.cenntro.common.mq.exception.RocketMQException;

/**
 * 生产者配置 .<br/>
 */
@Conditional(MQProducerCondition.class)
@SpringBootConfiguration
public class MQProducerConfiguration {
	public static final Logger LOGGER = LoggerFactory.getLogger(MQProducerConfiguration.class);
	@Resource
	private  com.cenntro.common.mq.config config;

	
	@Bean
	public DefaultMQProducer getRocketMQProducer() throws RocketMQException {
		if (StringUtils.isEmpty(config.getProducerGroupName())) {
			throw new RocketMQException(RocketMQErrorEnum.PARAMM_NULL, "groupName is blank", false);
		}
		if (StringUtils.isEmpty(config.getNamesrvAddr())) {
			throw new RocketMQException(RocketMQErrorEnum.PARAMM_NULL, "nameServerAddr is blank", false);
		}
		DefaultMQProducer producer = new DefaultMQProducer(config.getProducerGroupName());
		producer.setNamesrvAddr(config.getNamesrvAddr());
		// 如果需要同一个jvm中不同的producer往不同的mq集群发送消息，需要设置不同的instanceName
//		if (this.maxMessageSize != null) {
//			producer.setMaxMessageSize(this.maxMessageSize);
//		}
//		if (this.sendMsgTimeout != null) {
//			producer.setSendMsgTimeout(this.sendMsgTimeout);
//		}
		// 如果发送消息失败，设置重试次数，默认为2次
//		if (this.retryTimesWhenSendFailed != null) {
//			producer.setRetryTimesWhenSendFailed(this.retryTimesWhenSendFailed);
//		}

		try {
			producer.start();
			LOGGER.info(String.format("producer is start ! groupName:[%s],namesrvAddr:[%s]", config.getProducerGroupName(),
					config.getNamesrvAddr()));
		} catch (MQClientException e) {
			LOGGER.error(String.format("producer is error {}", e.getMessage(), e));
			throw new RocketMQException(e);
		}
		return producer;
	}
}